package com.msb.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.msb.order.exception.CommonException;
import com.msb.order.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class SentinelResourceController {

    //http://localhost:8001/testAspect/12
    @GetMapping("/testAspect/{id}")
    @SentinelResource(value = "testAspect",
            fallback = "fallback",fallbackClass = CommonException.class,
            blockHandler = "handleException",blockHandlerClass = CommonException.class
    )
    public Result testAspect(@PathVariable("id") Integer id){
        if(Integer.compare(id,Integer.parseInt("0")) == -1){
            throw new IllegalArgumentException("参数异常");
        }
        log.info("处理业务信息");
        return Result.ok("测试注解方式限流正常");
    }


    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        //设置受保护的资源
        rule.setResource("testAspect");
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);
        rules.add(rule);
        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }
}